/*
 * Copyright (C) 2010 mAPPn.Inc
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.mol.market.ui;

import java.util.ArrayList;
import java.util.HashMap;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.FrameLayout;
import android.widget.ListView;
import android.widget.ProgressBar;

import com.actionbarsherlock.app.SherlockFragment;
import com.mol.market.Constants;
import com.mol.market.R;
import com.mol.market.Session;
import com.mol.market.common.network.ApiAsyncTask.ApiRequestListener;
import com.mol.market.common.network.MarketAPI;
import com.mol.market.common.util.DialogUtil;
import com.mol.market.common.util.TopBar;
import com.mol.market.common.util.Utils;
import com.mol.market.common.vo.PayAndChargeLog;
import com.mol.market.common.vo.PayAndChargeLogs;
import com.mol.market.common.widget.LoadingDrawable;
import com.mol.market.demo.widget.BaseFragment;
import com.mol.market.demo.widget.BaseFragmentActivity;

/**
 * this view is displaying for login success to personal center
 * 
 * @author cong.li
 * @date 2011-5-17
 */
public class PersonalAccountFragment extends SherlockFragment implements
		OnItemClickListener, ApiRequestListener {

	private static final int ACCOUNT_REGIST = 0;
	private static final int ACCOUNT_BIND = 4;
	private static final int REQUEST_CODE = 20;
	// 登录成功
	public static final int LOGIN = 0;
	// 注销
	public static final int REGIST = 1;
	public static final int CLOUD_BIND = 2;
	public static final int CLOUD_UNBIND = 3;

	private BaseFragmentActivity mActivity;

	// 购买信息列表
	private ListView mList;
	private FrameLayout mLoading;

	private PersonalAccountAdapter mAdapter;
	private ProgressBar mProgress;
	// 是否正在云绑定
	private boolean isBinding;
	// 是否已经登陆过
	public boolean[] isFirstAccess = { true };

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		return initView(inflater, container);
	}

	public View initView(LayoutInflater inflater, ViewGroup container) {

		View root = inflater.inflate(R.layout.activity_person_account_layout,
				container, false);
		mList = (ListView) root.findViewById(android.R.id.list);

		mLoading = (FrameLayout) root.findViewById(R.id.loading);
		mProgress = (ProgressBar) mLoading.findViewById(R.id.progressbar);
		mProgress.setIndeterminateDrawable(new LoadingDrawable(getActivity()
				.getApplicationContext()));

		mAdapter = doInitPayAdapter();
		mList.setAdapter(mAdapter);
		mList.setItemsCanFocus(false);
		mList.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);

		mList.setOnItemClickListener(this);
		return root;
	}

	@Override
	public void onAttach(Activity activity) {
		super.onAttach(activity);
		mActivity = (BaseFragmentActivity) activity;
	}

	@Override
	public void onResume() {
		if (mActivity.mSession.isLogin() && isFirstAccess[0]) {
//			mProgress.setVisibility(View.VISIBLE);
//			MarketAPI.getBalance(getActivity().getApplicationContext(),
//					PersonalAccountActivity.this);
//			MarketAPI.getPayLog(getActivity().getApplicationContext(), this, 0,
//					10);
		}
		super.onResume();

	}

	@Override
	public void onPause() {
		if (Session.get(mActivity.getApplicationContext()).isLogin())
			isFirstAccess[0] = false;
		super.onPause();

	}

	public boolean getCurrentBindStatue() {
		return isBinding;
	}

	/*
	 * 初始化支付信息列表
	 */
	private PersonalAccountAdapter doInitPayAdapter() {

		return new PersonalAccountAdapter(this, getActivity()
				.getApplicationContext(), doInitFuncData(),
				R.layout.activity_personal_account_header_item, new String[] {
						Constants.ACCOUNT_ICON, Constants.ACCOUNT_TITLE,
						Constants.ACCOUNT_DESC, Constants.ACCOUNT_TIME,
						Constants.ACCOUNT_ARROW }, new int[] { R.id.iv_icon,
						R.id.tv_name, R.id.tv_description, R.id.tv_time,
						R.id.iv_arrow }, mHandler);
	}

	/*
	 * 初始化功能菜单栏数据
	 * 
	 * @return
	 */
	private ArrayList<HashMap<String, Object>> doInitFuncData() {
		ArrayList<HashMap<String, Object>> data = new ArrayList<HashMap<String, Object>>();

		int[] icons = new int[] { R.drawable.person_center_logo,
				R.drawable.person_center_payment };
		String[] titles = new String[] {
//				getString(R.string.account_logo_title),
//				getString(R.string.account_payment_title) };
				getString(R.string.account_logo_title)};

		String[] descs = new String[] { 
//				getString(R.string.account_logo_desc),
//				getString(R.string.account_payment_desc) };
				getString(R.string.account_logo_desc)};

//		for (int i = 0; i < 2; i++) {
		for (int i = 0; i < 1; i++) {
			HashMap<String, Object> map = new HashMap<String, Object>();
			map.put(Constants.ACCOUNT_ICON, icons[i]);
			map.put(Constants.ACCOUNT_TITLE, titles[i]);
			map.put(Constants.ACCOUNT_DESC, descs[i]);
			map.put(Constants.ACCOUNT_ARROW, R.drawable.more_indicator);
			map.put(Constants.ACCOUNT_TYPE, Constants.FLAG_HEADER_ITEM);
			data.add(map);
		}
		return data;
	}

	/*
	 * 将对象PayAndChargeLogs转换成所需的数据格式
	 */
	private ArrayList<HashMap<String, Object>> transferDataType(
			PayAndChargeLogs logs) {

		ArrayList<HashMap<String, Object>> data = null;
		ArrayList<PayAndChargeLog> logList = logs.payAndChargeLogList;
		if (logs != null && logList.size() > 0) {
			data = new ArrayList<HashMap<String, Object>>(logs.totalSize + 1);
			HashMap<String, Object> group = new HashMap<String, Object>();
			group.put(Constants.ACCOUNT_TYPE, Constants.FLAG_GROUP_ITEM);
			group.put(Constants.ACCOUNT_TIME, String.format(
					this.getString(R.string.account_payed_count),
					logs.totalSize));
			group.put(Constants.ACCOUNT_TITLE,
					this.getString(R.string.account_payed_history));
			group.put(Constants.KEY_PLACEHOLDER, true);
			data.add(group);
			for (PayAndChargeLog log : logList) {
				HashMap<String, Object> item = new HashMap<String, Object>();
				String url = log.iconUrl;
				item.put(Constants.ACCOUNT_ICON, url);
				item.put(Constants.ACCOUNT_TITLE, log.name);
				item.put(Constants.ACCOUNT_DESC, String.format(
						getString(R.string.gfan_money), log.payment));
				item.put(Constants.ACCOUNT_TIME, log.time + " "
						+ getString(R.string.account_payed));
				item.put(Constants.ACCOUNT_TYPE, log.type);
				data.add(item);
			}
		}
		return data;
	}

	@Override
	public void onSuccess(int method, Object obj) {
		switch (method) {
		// 获取支付信息
		case MarketAPI.ACTION_GET_PAY_LOG:
			PayAndChargeLogs logs = (PayAndChargeLogs) obj;
			if (logs != null && logs.totalSize > 0) {
				ArrayList<HashMap<String, Object>> data = transferDataType(logs);
				mAdapter.addData(data);
				mProgress.setVisibility(View.GONE);
			} else {
				mProgress.setVisibility(View.GONE);
				HashMap<String, Object> map = new HashMap<String, Object>();
				map.put(Constants.ACCOUNT_TYPE, Constants.FLAG_NO_PAY_LOG_ITEM);
				map.put(Constants.ACCOUNT_TITLE,
						getString(R.string.account_no_pay_log));
				mAdapter.addData(map);
			}
			break;

		// 绑定云推送
		case MarketAPI.ACTION_BIND_ACCOUNT:
			mActivity.mSession.setDeviceBinded(true);
			Utils.makeEventToast(getActivity().getApplicationContext(),
					getString(R.string.account_bind_success), true);
			HashMap<String, Object> cloud = mAdapter.getDataSource().get(1);
			cloud.put(Constants.ACCOUNT_DOWNLOAD, R.drawable.cloud_on);
			mAdapter.notifyDataSetChanged();
			isBinding = false;
			break;

		// 云推送解除绑定
		case MarketAPI.ACTION_UNBIND:
			break;

		// 获取帐号余额
//		case MarketAPI.ACTION_GET_BALANCE:
//			HashMap<String, Object> balanceMap = mAdapter.getDataSource()
//					.get(1);
//			balanceMap
//					.put(Constants.ACCOUNT_DESC,
//							getString(R.string.account_payment_balance,
//									obj.toString()));
//			mAdapter.notifyDataSetChanged();
//			break;

		default:
			break;
		}
	}

	private Handler mHandler = new Handler() {
		public void handleMessage(android.os.Message msg) {
			switch (msg.what) {
			// 注销
			case REGIST:
				ArrayList<HashMap<String, Object>> data = doInitFuncData();
				mAdapter.changeDataSource(data);
				break;
			case LOGIN:
				mAdapter.notifyDataSetChanged();
			}
		};
	};

	@Override
	public void onError(int method, int statusCode) {
		switch (method) {
		case MarketAPI.ACTION_BIND_ACCOUNT:
			Utils.W("bind account error");
			Utils.makeEventToast(getSherlockActivity().getApplicationContext(),
					getString(R.string.account_bind_error), true);
			HashMap<String, Object> map = mAdapter.getDataSource().get(1);
			map.put(Constants.ACCOUNT_DOWNLOAD, R.drawable.cloud_off);
			mAdapter.notifyDataSetChanged();
			break;

		default:

			// FIXBUG: 2011/9/15 修复注册完成没有刷新登录状态的Bug
			mAdapter.notifyDataSetChanged();
			break;
		}
	}

	// Heade Item的点击事件
	@Override
	public void onItemClick(AdapterView<?> parent, View view, int position,
			long id) {
		if (!mActivity.mSession.isLogin()) {
			goLoginActivity();
			return;
		}
		switch (position) {
		case 0:
			DialogUtil.createPersonalDialog(getSherlockActivity(), ACCOUNT_REGIST,
					isFirstAccess, mHandler, mAdapter).show();
			break;

		case 1:
			Utils.trackEvent(getSherlockActivity().getApplicationContext(),
					Constants.GROUP_9, Constants.CHARGE);
			String type = mActivity.mSession.getDefaultChargeType();
			if (type == null) {
				Intent intent = new Intent(mActivity,
						ChargeTypeListActivity.class);
				intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
				startActivity(intent);
			} else {
				Intent intent = new Intent(mActivity, PayMainActivity.class);
				intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
				intent.putExtra("type", type);
				startActivity(intent);
			}
			break;
		default:
			break;
		}
	}

	private void goLoginActivity() {
		Intent intent = new Intent(getSherlockActivity().getApplicationContext(),
				LoginActivity.class);
		startActivityForResult(intent, REQUEST_CODE);
	}

	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		mHandler.sendEmptyMessage(PersonalAccountFragment.LOGIN);
	}
}
